package cn.q3c.stock;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.xBaseJ.xBaseJException;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.keyvalue.ccf.common.util.ObjectUtils;
import cn.q3c.download.api.DownloadAPI;
import cn.q3c.download.commons.DownloadLog;
import cn.q3c.stock.commons.StockUtils;
import cn.q3c.stock.object.StockInfo;
import cn.q3c.stock.object.StockTradeLog;
import cn.q3c.stock.service.StockService;
import cn.q3c.stock.service.StockServiceImpl;

public class Run {

	private final static Logger logger = Logger.getLogger(Run.class);
	
	/**
	 * args[0]:1 入库当天行情数据 args[0]:2 入库历史所有的，用到之前的下载目录 如果是2，args[1]，数据目录
	 * 
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {

		if (NumberUtils.toInt(args[0]) == 1) {
			logger.info("开始进行当天交易数据的导入操作" + DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
			importToday();
		} else if (NumberUtils.toInt(args[0]) == 2) {
			logger.info("开始进行历史交易数据的导入操作" + args[1]);
			String datapath = args[1];
			importHistory(new File(datapath));
		}
	}

	private static StockService stockService = new StockServiceImpl();

	/**
	 * 采用 download 系统中数据 循环日志，解析出日期，代码和交易所
	 * @throws Exception 
	 * 
	 * @throws xBaseJException
	 */
	private static void importToday() throws Exception {
		
		//计算当天的日期，作出范围判断
		String dataFormat = "yyyy-MM-dd";
		SimpleDateFormat sdf = new SimpleDateFormat(dataFormat);
		Date toDate = sdf.parse(DateFormatUtils.format(
				System.currentTimeMillis(), dataFormat));
		Date fromDate = DateUtils.addDays(toDate, -2);

		//获取下载系统的文件日志，有5000个文件的上限
		List<DownloadLog> downloadLogList = DownloadAPI.getDownloadLogList(
				"StockJiaoYi", fromDate, toDate);
		
		//循环处理日志，由于service会自动根据日期判断是否已经写入，所以无需过滤
		if (!ObjectUtils.isEmptyList(downloadLogList)) {
			
			for (DownloadLog downloadLog : downloadLogList) {
				
				logger.debug("处理交易文件：" + downloadLog);
				
				Date tradeDate = getTradeDate(downloadLog);//交易日期
				String stockCode = getStockCode(downloadLog);//股票代码
				int sctype = getSctype(downloadLog);//交易所
				
				logger.debug("  交易日期：" + tradeDate);
				logger.debug("  stockCode：" + stockCode);
				logger.debug("  sctype：" + sctype);

				int stockid = stockService.stockCodeToSystemStockID(sctype, stockCode);
				
				logger.debug("  系统分配股票代码stockid：" + stockid);
				
				if( stockid > 0 && FileUtils.sizeOf(downloadLog.getFile()) > FileUtils.ONE_KB)
				{
					List<StockTradeLog> stockTradeLogList = StockUtils
							.toStockTradeLogList(stockid, tradeDate,
									downloadLog.getFile());// 文件转换为对象列表
	
					logger.debug("  解析交易数据列表：" + stockTradeLogList.size());
					
					//处理日志列表（一只股票一天的交易数据）
					if (!ObjectUtils.isEmptyList(stockTradeLogList)) {
						stockService.processTradeOneDay(stockTradeLogList);
					}
				
				}
			}
		}
	}

	/**
	 * 迭代目录，解析出日期、代码和交易所
	 * @throws Exception 
	 */
	private static void importHistory(File file) throws Exception
	{
		if (file.isFile()) {
			Date tradeDate = getTradeDate(file);
			String stockCode = getStockCode(file);
			int sctype = getSctype(file);

			int stockid = stockService.stockCodeToSystemStockID(sctype, stockCode);
			
			if( stockid > 0 && FileUtils.sizeOf(file) > FileUtils.ONE_KB )//合法性
			{
			
				logger.debug("处理交易文件：" + file);
				logger.debug("  交易日期：" + tradeDate);
				logger.debug("  stockCode：" + stockCode);
				logger.debug("  sctype：" + sctype);
				logger.debug("  系统分配股票代码stockid：" + stockid);
				
				List<StockTradeLog> stockTradeLogList = StockUtils
						.toStockTradeLogList(stockid, tradeDate, file);// wait
	
				logger.debug("  解析交易数据列表：" + stockTradeLogList.size());
				
				if (!ObjectUtils.isEmptyList(stockTradeLogList)) {
					stockService.processTradeOneDay(stockTradeLogList);
				}
			
			}
		} else if (file.isDirectory()) {
			File[] fileList = file.listFiles();
			if (ArrayUtils.isNotEmpty(fileList)) {
				for (File subFile : fileList) {
					importHistory(subFile);
				}
			}
		}
	}

	private static Date getTradeDate(File file) throws ParseException {
		String dateStr = StringUtils.substringBetween(file.getName(), "_", ".");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.parse(dateStr);
	}

	private static Date getTradeDate(DownloadLog downloadLog) throws ParseException {
		
		//http://market.finance.sina.com.cn/downxls.php?date=2013-07-09&symbol=sh600717
		String dateStr = StringUtils.substringBetween(downloadLog.getUrl(), "date=", "&");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.parse(dateStr);
	}

	private static String getStockCode(DownloadLog downloadLog) {
		String longCode = StringUtils.substringAfter(downloadLog.getUrl(), "symbol=");		
		return StringUtils.substring(longCode, 2);
	}

	private static String getStockCode(File file) {
		String code = StringUtils.substring(file.getName(), 2,8);
		return code;
	}

	private static int getSctype(File file) {
		
		int sctype = StringUtils.startsWith(file.getName(), "sh")?StockInfo.SC_SHANGHAI:StockInfo.SC_SHENZHEN;
		return sctype;
	}

	private static int getSctype(DownloadLog downloadLog) {
		String longCode = StringUtils.trimToEmpty(StringUtils.substringAfter(downloadLog.getUrl(), "symbol="));
		int sctype = StringUtils.startsWith(longCode, "sh")?StockInfo.SC_SHANGHAI:StockInfo.SC_SHENZHEN;
		return sctype;
	}
	
	
//	public static void main( String[] args )
//	{
//		System.out.println( StringUtils.substring("sh600717", 2) );
//	}

}
